package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.mkt.BidBondRecycleDto;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.ProcessService;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.mkt.jsonvo.BidBondRecycleJsonVo;
import top.infopub.mgr.mkt.service.BidBondRecycleService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.mkt.BidBondRecycle;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 保证金回收管理
 */
@Controller
@RequestMapping("/bidBondRecycle")
public class BidBondRecycleController extends GenericFlowController {

    @Autowired
    private BidBondRecycleService bidBondRecycleService;

    @Autowired
    private ProcessService processService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    /**
     * 根据id查询资格预审详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 资格预审Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request, String id, String proCode, String bondApplyId){
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id", id);
        request.setAttribute("bondApplyId", bondApplyId);
        request.setAttribute("auditTabFlag", "0");
        request.setAttribute("isAuditFlag", "1");
        if (StringUtils.isNotBlank(id)) {
            BidBondRecycle bbr = bidBondRecycleService.selectByPrimaryKey(id);
            if (bbr != null) {
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bbr.getProcessStatus())
                        || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), bbr.getProcessStatus())) {
                    request.setAttribute("isAuditFlag", "0");
                }
                if (StringUtils.isNotBlank(bbr.getProcessId()) && bbr.getProcessId().length() > 10) {
                    request.setAttribute("processId", bbr.getProcessId());
                    String auditTabFlag = proProcessManageService.checkShowAuditTab(bbr.getProcessId(), vo);
                    if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bbr.getProcessStatus())
                            && StringUtils.equals("0", auditTabFlag)) {
                        request.setAttribute("isAuditFlag", "0");
                    }
                    request.setAttribute("auditTabFlag", auditTabFlag);
                }
            }
        }
        request.setAttribute("proCode", proCode);
        return "mkt/lay-marginRecovery-detail";
    }

    @RequestMapping("/queryRecycleDetail")
    @ResponseBody
    public RspVo queryDetailByProCode(String id, String proCode, String bondApplyId) {
        BidBondRecycleJsonVo bidRecJson;
        if (StringUtils.isNotBlank(id)) {
            //保证金回收详情信息-财务填写信息
            bidRecJson = bidBondRecycleService.queryDetailById(id);
        } else {
            //保证金回收详情信息-财务填写信息
            bidRecJson = bidBondRecycleService.queryDetailByProCode(proCode, bondApplyId);
        }
        return RspVo.getSuccessResponse(bidRecJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //保证金回收审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑招标文件分析
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(HttpServletRequest request, String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        BidBondRecycleJsonVo bidRecJson = JSON.parseObject(str, BidBondRecycleJsonVo.class);
        BidBondRecycleDto bidRecDto = bidRecJson.getInfo();
        //更新保证金回收-MKT_BID_BOND_RECYCLE
        BidBondRecycle bidBondRecycle = new BidBondRecycle();
        BeanUtils.copyProperties(bidRecDto, bidBondRecycle);

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(bidRecJson.getFileAtt()!=null){
            String[] fileAtt = bidRecJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, bidRecDto.getProCode(), file);
                attachmentList.add(attachment);
            }
        }

        //调用service进行数据库操作
        RspVo rspVo = bidBondRecycleService.editDetail(bidBondRecycle, attachmentList, vo, submitType);
        return rspVo;
    }

    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if(StringUtils.isEmpty(types)){
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "inquiryProAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types+"|"+file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传资格预审附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
